require 'infolr_log'
require 'thread'
require 'greader/google_reader_api'

module Infolr
  class Crawler
    def self.update
      t = Thread.new do
        crawler_thread = Thread.new do
          while true do
              $logger.debug "start fetching feed data from server..."
              self.fetch_feeds
              sleep 10
              $logger.debug "complete fetching feed data from server."
          end
        end
      end       
      t.join # wait for thread to exit (never, in this case) 
    end    
    # fetch feeds data from google reader
    def self.fetch_feeds
      email = 'infoleacher@gmail.com'
      password = 'youyou'
      $logger.debug "login to google reader"
      @cookie = GoogleReaderApi.login(email,password)
      $logger.debug "login succeeded."
      @token = GoogleReaderApi.get_token(@cookie) 
      $logger.debug "fetching feed data from google reader"
      reading_list = GoogleReaderApi.get_reading_list(@cookie)
      $logger.debug "google reader reading list has been fecthed to local and now parsing begin."
      tempfile = Tempfile.new(File.join("#{RAILS_ROOT}", "tmp", "tempfile"))
      tempfile << reading_list
      $logger.debug "reading list is: #{reading_list}"
      tempfile.rewind
      feed_entries = Infolr::ReadingListParser.stream_parse(tempfile)
      tempfile.close
      $logger.debug "#{feed_entries.length} feed entries will be processed."
      counter = 0
      feed_entries.each do |feed_entry|
        $logger.debug "#{counter} feed entry #{feed_entry.link} is processed."
        counter += 1
        Infolr::RssAccessor.add_item(feed_entry)
        GoogleReaderApi.read_item(@cookie,@token,feed_entry)
      end
  end
  end
end
$logger.info "feed updating..."
Infolr::Crawler.update